package com.ithuameng.cosy.coder.protobuf;

import com.ithuameng.cosy.model.Transportable;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufAllocator;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToMessageEncoder;
import io.netty.handler.codec.http.websocketx.BinaryWebSocketFrame;

import java.util.List;

/**
 * websocket协议 protobuf消息体编码
 *
 * @author ithuameng
 */
public class WebMessageEncoder extends MessageToMessageEncoder<Transportable> {

    @Override
    protected void encode(ChannelHandlerContext ctx, Transportable data, List<Object> out) {
        byte[] body = data.getBody();
        ByteBufAllocator allocator = ctx.channel().config().getAllocator();
        ByteBuf buffer = allocator.buffer(body.length + 1);
        buffer.writeByte(data.getType().getValue());
        buffer.writeBytes(body);
        out.add(new BinaryWebSocketFrame(buffer));
    }
}
